/**
 * user
 */
import {userService} from '../../service/userService'
import {Notice} from '../../tools/notification'
import {Auth} from './auth'

const defaultUser = {login: '', password: '', remember: false}

export default {
  state: {
    /** token */
    token: Auth.getToken() || null,
    /** 用户登陆角色信息 */
    userInfo: Auth.getUserInfo() || {},
    /** 用户登陆账户密码 */
    accountPwd: Auth.getPassword() || defaultUser,
    /** 是否登陆 */
    isLogin: Auth.getLogin() || false,
    /** 角色权限点 */
  },
  /** 计算属性 */
  getters: {},
  /** 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation */
  mutations: {
    ACCOUNT_AUTH_STATUS_CHANGED (state, data) {
      if (data.params.remember) {
        state.password = data.params
        Auth.setPassword(data.params)
      }
      // state.token = data.token;
      state.userInfo = data.data.data
      state.isLogin = true
      Auth.setUserInfo(JSON.stringify(data.data.data))
      Auth.setLogin()
      // Auth.setToken(data.token)
    },
    ACCOUNT_LOGOUT_FAILURE (state) {
      state.token = null
      state.userInfo = {}
      state.password = {}
      state.permission = []
      state.isLogin = false
      Auth.removePassword()
      Auth.removeUserInfo()
      Auth.removeLogin()
      Auth.removeToken()
    }
  },
  /** Action 提交的是 mutation，而不是直接变更状态。Action 可以包含任意异步操作。 */
  actions: {
    /** 登录 */
    loginSubmit ({commit}, params) {
      return new Promise((resolve, reject) => {
        userService.login(params).then((res) => {
          if (res.data.status) {
            commit('ACCOUNT_AUTH_STATUS_CHANGED', {...res, params})
            Notice.success('登录成功')
            resolve()
          } else {
            Notice.warn('此账户无访问权限，请登录其他账户设置')
            reject('此账户无访问权限，请登录其他账户设置')
          }
        }).catch(err => {
          reject(err)
          commit('ACCOUNT_LOGOUT_FAILURE')
        })
      })
    },
    /** 登出 */
    accountLogoutSubmit ({commit}) {
      return new Promise((resolve, reject) => {
        userService.loginout().then((res) => {
          commit('ACCOUNT_LOGOUT_FAILURE')
          resolve()
        }).catch(err => {
          commit('ACCOUNT_LOGOUT_FAILURE')
          resolve()
        })
      })
    },
  }
}
